<template>
    <div>
        <!-- 菜单按钮 -->
        <!-- <el-button @click="showReport('year')">年度报表</el-button>
      <el-button @click="showReport('month')">月度报表</el-button> -->

        <!-- Tab页 -->
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <!-- 年度报表 Tab -->
            <el-tab-pane label="年度报表" name="year">
                <div v-show="activeTab === 'year'">
                    <!-- 搜索相关 start -->
                    <el-form :model="queryParams" size="default" :inline="true" v-show="showSearch" label-width="38px">
                        <el-form-item label="年份" prop="user" label-width="70px">
                            <el-date-picker v-model="selectedYear" type="year" placeholder="请选择年份" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="default"
                                @click="handleGetYearList">搜索</el-button>
                        </el-form-item>
                    </el-form>
                    <!-- 搜索相关 end -->

                    <!-- 图表 -->
                    <div ref="yearChartRef" style="width: 100%; height: 400px;"></div>
                </div>
            </el-tab-pane>

            <!-- 月度报表 Tab -->
            <el-tab-pane label="月度报表" name="month">
                <div v-show="activeTab === 'month'">
                    <!-- 搜索相关 start -->
                    <el-form :model="queryParams" size="default" :inline="true" v-show="showSearch" label-width="38px">
                        <el-form-item label="年份" prop="user" label-width="70px">
                            <el-date-picker v-model="selectedYearMonth" type="month" placeholder="请选择年月份" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="default"
                                @click="handleGetMonthList">搜索</el-button>
                        </el-form-item>
                    </el-form>
                    <!-- 搜索相关 end -->

                    <!-- 图表 -->
                    <div ref="monthChartRef" style="width: 100%; height: 400px;"></div>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount, reactive, nextTick } from 'vue';
import { showErrorMsg, showSuccessMsg, formatDate, indexMethod } from '@/api/common';
import type { OnlyIdRequest, ApiResponse } from '@/api/common';
import * as echarts from 'echarts';
import type { QuerySummaryParams, AccountingSummaryVo } from '@/api/accounting/accounting';
import { yearSummary, monthSummary } from '@/api/accounting/accounting';

// 定义响应式数据
const activeTab = ref<string>('year'); // 默认选中的 Tab

// 切换报表类型
const handleTabClick = (tab: string) => {
    destroyChart();
    activeTab.value = tab;
};

// 搜索相关
const showSearch = ref(true);
const selectedYear = ref('');
const selectedYearMonth = ref('')
let queryParams = reactive<QuerySummaryParams>({
    accountingYear: null,
    accountingMonth: null,
});

// chart相关
const yearChartRef = ref<HTMLDivElement | null>(null);
const monthChartRef = ref<HTMLDivElement | null>(null);
const yearChartData = ref<{ categories: string[]; values: number[] }>({
    categories: [], // 初始化xAxis的数据
    values: [] // 初始化series的数据
});
const monthChartData = ref<{ categories: string[]; values: number[] }>({
    categories: [], // 初始化xAxis的数据
    values: [] // 初始化series的数据
});
const handleGetYearList = () => {
    if (!selectedYear.value) {
        showErrorMsg('请选择年份');
        return;
    }
    let selectedYearMonthTemp = formatDate(selectedYear.value);
    let yearMonthTemp = selectedYearMonthTemp.split('-');
    queryParams.accountingYear = parseInt(yearMonthTemp[0], 10);
    yearSummary(queryParams).then((res: ApiResponse<AccountingSummaryVo>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            if (res.data && res.data.xseries) {
                // 用下面这个直接赋值，反而有问题，不知为何。
                // chartData.value.categories = [];
                // chartData.value.values = [];
                yearChartData.value.categories.length = 0;
                yearChartData.value.values.length = 0;
                res.data.xseries.map(x => yearChartData.value.categories.push(x));
                res.data.yseries.map(x => yearChartData.value.values.push(x));
                reloadYearChart();
                // 监听窗口变化，重新调整图表尺寸
                window.addEventListener('resize', resizeYearChart);
            }
        }
    });
};
const handleGetMonthList = () => {
    if (!selectedYearMonth.value) {
        showErrorMsg('请选择年月份');
        return;
    }
    let selectedYearMonthTemp = formatDate(selectedYearMonth.value);
    let yearMonthTemp = selectedYearMonthTemp.split('-');
    queryParams.accountingYear = parseInt(yearMonthTemp[0], 10);
    queryParams.accountingMonth = parseInt(yearMonthTemp[1], 10);
    monthSummary(queryParams).then((res: ApiResponse<AccountingSummaryVo>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            if (res.data && res.data.xseries) {
                // 用下面这个直接赋值，反而有问题，不知为何。
                // chartData.value.categories = [];
                // chartData.value.values = [];
                monthChartData.value.categories.length = 0;
                monthChartData.value.values.length = 0;
                res.data.xseries.map(x => monthChartData.value.categories.push(x));
                res.data.yseries.map(x => monthChartData.value.values.push(x));
                reloadMonthChart();
                // 监听窗口变化，重新调整图表尺寸
                window.addEventListener('resize', resizeMonthChart);
            }
        }
    });
};
const yearChartOptions = {
    title: { text: '年度汇总', left: 'center' },
    tooltip: {},
    xAxis: { type: 'category', data: yearChartData.value.categories },
    yAxis: { type: 'value' },
    series: [{ name: '金额', type: 'bar', data: yearChartData.value.values }],
};
const monthChartOptions = {
    title: { text: '月度汇总', left: 'center' },
    tooltip: {},
    xAxis: { type: 'category', data: monthChartData.value.categories },
    yAxis: { type: 'value' },
    series: [{ name: '金额', type: 'bar', data: monthChartData.value.values }],
};
let yearChart: echarts.ECharts | null = null; // 图表实例
let monthChart: echarts.ECharts | null = null; // 图表实例

// 销毁图表实例
const destroyChart = () => {
    if (yearChart) {
        yearChart.dispose();
        yearChart = null; // 清除图表实例
    }
    if (monthChart) {
        monthChart.dispose();
        monthChart = null; // 清除图表实例
    }
};

// 重新加载图表
const reloadYearChart = () => {
    if (yearChart) {
        destroyChart(); // 先销毁旧的图表实例
    }
    // 重新初始化图表
    if (yearChartRef.value && yearChartRef.value.clientWidth > 0 && yearChartRef.value.clientHeight > 0) {
        yearChart = echarts.init(yearChartRef.value);
        yearChart.setOption(yearChartOptions);

        // 延迟触发 resize，确保图表容器已渲染完成
        nextTick(() => {
            yearChart?.resize();
        });
    }
};
// 重新加载图表
const reloadMonthChart = () => {
    if (monthChart) {
        destroyChart(); // 先销毁旧的图表实例
    }
    // 重新初始化图表
    if (monthChartRef.value && monthChartRef.value.clientWidth > 0 && monthChartRef.value.clientHeight > 0) {
        monthChart = echarts.init(monthChartRef.value);
        monthChart.setOption(monthChartOptions);

        // 延迟触发 resize，确保图表容器已渲染完成
        nextTick(() => {
            monthChart?.resize();
        });
    }
};

onBeforeUnmount(() => {
    destroyChart(); // 在组件销毁时销毁图表实例，避免内存泄漏
});

const resizeYearChart = () => {
    if (yearChart) {
        yearChart.resize(); // 调整图表大小
    }
};
const resizeMonthChart = () => {
    if (monthChart) {
        monthChart.resize(); // 调整图表大小
    }
};
</script>
<style scoped></style>